package com.hxl.access.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>SQl工具</p>
 *
 * @author By: zhangchunyang
 * Package com.yang.transformutils.utils
 */
@Slf4j
public class SqlAccessUtil {

    /**
     * 增、删、改
     *
     * @param dbUrl  数据库连接地址
     * @param sql    Sql语句
     * @param params 参数
     * @return
     * @throws SQLException
     */
    public static boolean insertAndUpdateAndDelete(String dbUrl, String sql, List<Object> params) throws SQLException {
        int result = -1;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = AccessDBUtils.getConnection(dbUrl);
            assert conn != null;
            ps = conn.prepareStatement(sql);
            int index = 1;
            if (!CollectionUtils.isEmpty(params)) {
                for (Object param : params) {
                    ps.setObject(index++, param);
                }
            }
            result = ps.executeUpdate();
        } catch (Exception e) {
            log.error("SqlUtil insertAndUpdateAndDelete Exception", e);
            try {
                assert conn != null;
                conn.rollback();
            } catch (SQLException e1) {
                log.error("SqlUtil insertAndUpdateAndDelete rollback SQLException", e1);
            }
            throw e;
        } finally {
            AccessDBUtils.close(conn, ps, null);
        }
        return result > 0;
    }

    /**
     * 查询多条记录
     *
     * @param dbUrl  数据库连接地址
     * @param sql    sql
     * @param params 参数
     * @return 查询结果
     * @throws SQLException
     */
    public static List<Map<String, Object>> select(String dbUrl, String sql, List<Object> params) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        int index = 1;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = AccessDBUtils.getConnection(dbUrl);
            assert conn != null;
            ps = conn.prepareStatement(sql);
            if (params != null && !params.isEmpty()) {
                for (Object param : params) {
                    ps.setObject(index++, param);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int col_len = metaData.getColumnCount();
            Map<String, Object> map = null;
            while (rs.next()) {
                map = new HashMap<>();
                for (int i = 0; i < col_len; i++) {
                    String cols_name = metaData.getColumnName(i + 1);
                    Object cols_value = rs.getObject(cols_name);
                    if (cols_value == null) {
                        cols_value = "";
                    }
                    map.put(cols_name, cols_value);
                }
                list.add(map);
            }
        } catch (Exception e) {
            log.error("SqlUtil select Exception", e);
            throw e;
        } finally {
            AccessDBUtils.close(conn, ps, rs);
        }
        return list;
    }

    /**
     * 通过反射机制查询多条记录
     *
     * @param dbUrl  数据库连接
     * @param sql    sql
     * @param params 参数
     * @param clazz  类class
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> select(String dbUrl, String sql, List<Object> params, Class<T> clazz) throws Exception {
        List<T> list = new ArrayList<>();
        int index = 1;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = AccessDBUtils.getConnection(dbUrl);
            assert conn != null;
            ps = conn.prepareStatement(sql);
            if (params != null && !params.isEmpty()) {
                for (Object param : params) {
                    ps.setObject(index++, param);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int cols_len = metaData.getColumnCount();
            T t;
            while (rs.next()) {
                t = clazz.newInstance();
                for (int i = 0; i < cols_len; i++) {
                    String cols_name = metaData.getColumnName(i + 1);
                    Object cols_value = rs.getObject(cols_name);
                    if (cols_value == null) {
                        cols_value = "";
                    }
                    Field field = clazz.getDeclaredField(cols_name);
                    field.setAccessible(true);
                    field.set(t, cols_value);
                }
                list.add(t);
            }
        } catch (Exception e) {
            log.error("SqlUtil reflect select Exception", e);
            throw e;
        } finally {
            AccessDBUtils.close(conn, ps, rs);
        }
        return list;
    }

    /**
     * 动态从数据文件中获取所有的表名
     *
     * @param dbUrl 数据库连接
     */
    public static void getAllTables(String dbUrl) {
        try {
            Connection conn = AccessDBUtils.getConnection(dbUrl);

            DatabaseMetaData metadata = conn.getMetaData();

            ResultSet tables = metadata.getTables(null, null, "%", null);
            while (tables.next()) {
                log.info("all tables is : {}", tables.getString(3));
            }
            tables.close();
            conn.close();
        } catch (Exception e) {
            log.error("SqlUtil getAllTables Exception", e);
        }
    }

    /**
     * 读取指定表信息
     *
     * @param dbUrl     数据地址
     * @param tableName 表名
     * @throws Exception
     */
    public static List readTableData(String dbUrl, String tableName) throws Exception {
        String mdbSql = "SELECT * FROM " + tableName;
        List<Map<String, Object>> list = resolverMdb(dbUrl, mdbSql);
        return list;
    }

    /**
     * 动态获取字段及属性值
     *
     * @param dbUrl 数据地址
     * @param sql   mdb查询字段
     * @return
     * @throws Exception
     */
    private static List<Map<String, Object>> resolverMdb(String dbUrl, String sql) throws Exception {

        if (dbUrl.isEmpty() || sql.isEmpty()) {
            throw new Exception("");
        }
        List<Map<String, Object>> mdbEntityList = new ArrayList<>();
        java.util.Properties prop = new java.util.Properties();
        prop.put("charSet", "UTF-8");
        try {
            Connection conn = AccessDBUtils.getConnection(dbUrl, prop);
            Statement statement = conn.createStatement();
            ResultSet result = statement.executeQuery(sql);
            ResultSetMetaData metaData = result.getMetaData();
            int count = metaData.getColumnCount();
            List<String> mdbColumnList = new ArrayList<String>(count);
            //动态解析字段名
            for (int i = 1; i <= count; i++) {
                mdbColumnList.add(metaData.getColumnName(i));
            }
            //解析执行结果
            Map<String, Object> mdbMapList = new HashMap<>(16);

            while (result.next()) {
                StringBuffer sb = new StringBuffer();
                for (String col : mdbColumnList) {
                    sb.append("col==" + result.getObject(col)).append("\t");
                    mdbMapList.put(col, result.getObject(col));
                }
                if (log.isDebugEnabled()) {
                    log.debug("------ is : {}", sb.toString());
                }
                mdbEntityList.add(mdbMapList);
            }
        } catch (Exception e) {
            log.error("SqlUtil resolverMdb Exception", e);
        }
        return mdbEntityList;
    }
}
